Page({
  data: {
    //页码
    tempPage: 1, // 临时存储输入的页码
    pageSize: 3, // 每页显示条数
    totalPages: 3,
    currentPageData: [], // 当前页数据
    //管理是否完成
    isBatchMode: false,
    // 搜索框
    searchText: '', 
    //已完成未完成统计
    currentCollectionTab: 'all', // 默认显示全部
    totalCount: 0,
    completedCount: 0,
    uncompletedCount: 0,
    //tab标签
    tabs: ['全部','副本','任务','伙伴','功绩','头衔箱子','媒体礼包','小猫箱子','技能','换装间','商城','活动','活动+商城','纹章收集','装备任务'],
    currentTab: 0,
    //副本选择框
    isPickerVisible: false,
    Dungeondisabled:false,
    districtMap:[],
    area:[],
    selectedArea: null,
    selectedAreaIndex: 0,
    Dungeon:[],
    selectedDungeon: null,
    selectedDungeonIndex: 0,
    //头衔详细属性
    showPopup: false,
    TitleAttributes:[
      {lable:'力量',value:'strength'},
      {lable:'敏捷',value:'agility'},
      {lable:'智力',value:'intelligence'},
      {lable:'意志',value:'willpower'},
      {lable:'生命力',value:'vitality'},
      {lable:'攻击力',value:'attack'},
      {lable:'魔法攻击力',value:'magicAttack'},
      {lable:'伤害平衡',value:'damageBalance'},
      {lable:'暴击',value:'critical'},
    ],
    //头衔集合
    titles: [
      {
        name: '荣耀战士',//头衔名称
        tagName: '副本',//类型
        tagClass: '全角色',//角色限制
        description: '在竞技场中获得 2000 分以上的评级',//获取方法
        area: '以外地区？艾因拉赫',//副本地区
        Dungeon:'可在〔角色 ? 功绩〕中查询对应副本',//副本名称
        completed: true,//是否完成
        isSelected: false,//是否选择
        strength:1,//力量
        agility:2,
        intelligence:3,
        willpower:4,
        vitality:5,
        attack:6,
        magicAttack:6,
        damageBalance:7,
        critical:8,
      },
      {
        name: '探索大师',
        tagName: '探索',
        tagClass: '全角色',
        description: '探索所有主城地图的隐藏地点',
        area: '以外地区？艾因拉赫',//副本地区
        Dungeon:'可在〔角色 ?123〕中查询对应副本',//副本名称
        completed: false,
        isSelected: false
      },
      {
        name: '传说收藏家',
        tagName: '成就',
        tagClass: 'achievement',
        description: '收集 100 个传说装备',
        area: '以外地区？123',//副本地区
        Dungeon:'可在〔角色 ?123〕中查询对应副本',//副本名称
        completed: false,
        isSelected: false
      },
      {
        name: '传说收藏家',
        tagName: '成就',
        tagClass: 'achievement',
        description: '收集 100 个传说装备',
        area: '以外地区？123',//副本地区
        Dungeon:'可在〔角色 ?123〕中查询对应副本',//副本名称
        completed: false,
        isSelected: false
      }
    ],
    FilteredTitles:[],
    //分页
    currentPage: 1,
    tabBarItems: [
      { icon: 'home', text: '首页' },
      { icon: '/images/heart.png', text: '收藏' },
      { icon: '/images/person.png', text: '我的' }
    ],
    currentTabBar: 0
  },

  onLoad: function() {
    // 页面加载时读取数据库
    this.getTitleArrarys();
  },
  getTitleArrarys(){
    /* 获取数据接口 存入总集合、筛选集合 */
    //获取副本地区和副本名称集合
    const { titles } = this.data;
    const districtMap = {};
    const areaArray = ['全部'];
    titles.forEach(title => {
      const { area, Dungeon } = title;
      if (!districtMap[area]) {
        districtMap[area] = [];
        areaArray.push(area);
      }
      if (!districtMap[area].includes(Dungeon)){
        districtMap[area].push(Dungeon);
      }
    });
    this.setData({ districtMap,area:areaArray });
    // 统计信息
    this.FilteredTitles();
  },
  //进入、退出完成管理
  toggleBatchMode() {
    const newMode = !this.data.isBatchMode;
    this.setData({
      isBatchMode: newMode,
      selectedCount: 0,
      'FilteredTitles': this.data.FilteredTitles.map(item => ({
        ...item,
        isSelected: false,
      })),
      'titles': this.data.titles.map(item => ({
        ...item,
        isSelected: false,
      })),
    });
  },
  handleCheckboxTap(e) {
    const index = e.currentTarget.dataset.index;
    const { FilteredTitles,titles } = this.data;
    // 检查索引是否在有效范围内
    if (index >= 0 && index < FilteredTitles.length) {
      FilteredTitles[index].isSelected = !FilteredTitles[index].isSelected;
      titles[index].isSelected = !titles[index].isSelected;
      this.setData({ FilteredTitles,titles });
    } else {
      console.error('Index out of range:', index);
    }
  },
  //通过头衔名称搜索
  handleSearchInput(e){
    this.setData({ searchText: e.detail.value });
  },
  searchForName(){
    if (!this.data.searchText.trim()) {
      wx.showToast({
        title: '搜索内容为空，已搜索全部，请输入关键词搜索',
        icon: 'none', // 设置图标类型为无图标
        duration: 2000 // 提示框显示的时长，单位为毫秒
      });
      this.FilteredTitles();
      return;
    }
    this.FilteredTitles();
  },
  //切换 [全部 副本...]导航栏
  onTabClick: function(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentTab: index
    },() => {
        // 触发筛选方法，筛选所有条件,并统计个数
        this.FilteredTitles();
    });
  },
  //点击筛选 全部、已完成、未完成
  switchCollectionTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentCollectionTab: tab,
      selectedCount: 0,
    },() => {
      // 触发筛选方法，筛选所有条件
      this.FilteredTitles();
    });
  },
  // 筛选方法，筛选所有条件,并统计个数
  FilteredTitles(){
    this.setData({FilteredTitles:[],});
    //筛选
    const FilteredTitles = this.data.titles.filter(title => {
      const { currentTab,currentCollectionTab,searchText } = this.data;
      let match = true;
      if(currentTab != 0){ 
        match = match && title.tagName === this.data.tabs[this.data.currentTab];
      }
      if(currentCollectionTab != 'all'){ 
        if(currentCollectionTab == 'completed'){
          match = match && title.completed;
        } else {
          match = match && !title.completed;
        }
      }
      if(searchText.trim()){ 
        match = match && title.name.includes(searchText);
      }
      return match;
    });
    this.setData({
      FilteredTitles:FilteredTitles,
    },()=>{
      //统计参数
      const allTitles = this.data.FilteredTitles.length;
      const totalPage = Math.ceil(allTitles / this.data.pageSize)
      this.setData({
        totalCount:allTitles,
        totalPages:totalPage,
      },()=>{ this.loadPageData();})//分页
    })
  },
  showRegionPicker() {
    this.setData({ isPickerVisible: true });
  },
  hidePicker() {
    this.setData({ isPickerVisible: false });
  },
  confirmPicker() {
    const { regions, selectedRegionIndex } = this.data;
    const selectedRegion = regions[selectedRegionIndex];
    this.setData({ selectedRegion,isPickerVisible: false });
  },
  // 处理副本区域选择
  handleareaChange(e) {
    const selectedAreaIndex = e.detail.value;
    const area = this.data.area;
    const selectedArea = selectedAreaIndex == 0 ? null : area[selectedAreaIndex];
    const Dungeon = this.getDungeonByArea(selectedArea);
    const Dungeondisabled = selectedAreaIndex == 0 ? false : true;
    this.setData({
      selectedAreaIndex,
      selectedArea:selectedArea,
      Dungeon,
      selectedDungeon: null,
      selectedDungeonIndex: 0,
      Dungeondisabled,
    });
  },
  handleDungeonChange(e){
    const selectedDungeonIndex = e.detail.value;
    const Dungeon = this.data.Dungeon;
    const selectedDungeon = Dungeon[selectedDungeonIndex];

    this.setData({
      selectedDungeonIndex,
      selectedDungeon,
    });
  },

  //根据副本地区筛选副本名称
  getDungeonByArea(selectedArea) {
    const {districtMap} = this.data;
    return districtMap[selectedArea] || [];
  },

  //切换底部导航栏
  switchTabBar(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentTabBar: index
    });
  },

  showPopupWithOtherTitles: function(e) {
    const selectedIndex = e.currentTarget.dataset.index;
    const filteredTitles = this.data.titles.filter((_, index) => index === selectedIndex);
    if(!this.data.isBatchMode){
      this.setData({
        showPopup: true,
        filteredTitles: filteredTitles,
        selectedIndex: selectedIndex
      });
    }else{//编辑完成情况

    }
  },
  hidePopup: function() {
    this.setData({
      showPopup: false,
      filteredTitles: [],
      selectedIndex: null
    });
  },
  // 监听输入框
  handlePageInput(e) {
    const page = parseInt(e.detail.value);
    this.setData({ tempPage: page || 1 });
  },
  //上一页
  prevPage() {
    if (this.data.currentPage > 1) {
      this.setData({ currentPage: this.data.currentPage - 1 }, () => {
        this.loadPageData();
      });
    }
  },
  // 下一页
  nextPage() {
    if (this.data.currentPage < this.data.totalPages) {
      this.setData({ currentPage: this.data.currentPage + 1 }, () => {
        this.loadPageData();
      });
    }
  },
  // 跳转到指定页
  jumpToPage() {
    let page = this.data.tempPage;
    if (page < 1) page = 1;
    if (page > this.data.totalPages) page = this.data.totalPages;
    
    this.setData({ 
      currentPage: page,
      tempPage: page
    }, () => {
      this.loadPageData();
    });
  },
  loadPageData() {
    const { FilteredTitles, currentPage, pageSize } = this.data;
    const start = (currentPage - 1) * pageSize;
    const end = start + pageSize;
    this.setData({
      currentPageData: FilteredTitles.slice(start, end),
    });
  },
  // 批量完成
  batchAddCompleted() {
    const { FilteredTitles, titles } = this.data;
    // 找出需要变更状态的对象
    const updatedFilteredTitles = FilteredTitles.filter(item => item.isSelected && !item.completed);
    const updatedTitles = [];
  
    // 更新 titles 数组中的对应项
    // updatedFilteredTitles.forEach(filteredTitle => {
    //   const foundIndex = titles.findIndex(title => title.name === filteredTitle.name);
    //   if (foundIndex !== -1) {
    //     const updatedTitle = { ...titles[foundIndex], completed: true };
    //     updatedTitles.push(updatedTitle);
    //     titles[foundIndex] = updatedTitle;
    //   }
    // });
  
    // 更新数据
    // this.setData({
    //   FilteredTitles: FilteredTitles.map(item => {
    //     const updatedItem = updatedFilteredTitles.find(filtered => filtered.name === item.name);
    //     return updatedItem || item;
    //   }),
    //   titles
    // }, () => {
    //   // 重新筛选和统计
    //   this.FilteredTitles();
    // });
  
    // 打印需要变更状态的对象
    console.log('需要变更状态的对象:', updatedFilteredTitles);
    // console.log('更新后的 titles 数组:', updatedTitles);
  },
  // 批量取消完成
  batchDeleteCompleted() {
    const { FilteredTitles, titles } = this.data;
    // 找出需要变更状态的对象
    const updatedFilteredTitles = FilteredTitles.filter(item => item.isSelected && item.completed);
    const updatedTitles = [];
  
    // 更新 titles 数组中的对应项
    // updatedFilteredTitles.forEach(filteredTitle => {
    //   const foundIndex = titles.findIndex(title => title.name === filteredTitle.name);
    //   if (foundIndex !== -1) {
    //     const updatedTitle = { ...titles[foundIndex], completed: false };
    //     updatedTitles.push(updatedTitle);
    //     titles[foundIndex] = updatedTitle;
    //   }
    // });
  
    // 更新数据
    // this.setData({
    //   FilteredTitles: FilteredTitles.map(item => {
    //     const updatedItem = updatedFilteredTitles.find(filtered => filtered.name === item.name);
    //     return updatedItem || item;
    //   }),
    //   titles
    // }, () => {
    //   // 重新筛选和统计
    //   this.FilteredTitles();
    // });
  
    // 打印需要变更状态的对象
    console.log('需要变更状态的对象:', updatedFilteredTitles);
    // console.log('更新后的 titles 数组:', updatedTitles);
  },
});
